package service;

import model.Movie;
import model.Seat;
import model.Show;
import model.Ticket;
import util.FileHandler;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class TicketService {
    private static final String TICKET_FILE = "tickets.dat";
    private List<Ticket> tickets;

    public TicketService() {
        tickets = FileHandler.loadData(TICKET_FILE);
        if (tickets == null) tickets = new ArrayList<>();
    }

    // 保存票务数据
    public void saveTickets() {
        FileHandler.saveData(tickets, TICKET_FILE);
    }

    // 列出所有票
    public List<Ticket> listAllTickets() {
        return new ArrayList<>(tickets);
    }

    // 根据票号获取票
    public Ticket getTicketById(String id) {
        for (Ticket ticket : tickets) {
            if (ticket.getId().equals(id)) {
                return ticket;
            }
        }
        return null;
    }

    // 根据场次ID获取票
    public List<Ticket> getTicketsByShowId(String showId) {
        List<Ticket> result = new ArrayList<>();
        for (Ticket ticket : tickets) {
            if (ticket.getShowId().equals(showId) && !ticket.isRefunded()) {
                result.add(ticket);
            }
        }
        return result;
    }

    // 检查场次是否有售票
    public boolean hasTickets(String showId) {
        return !getTicketsByShowId(showId).isEmpty();
    }

    // 售票
    public Ticket sellTicket(Show show, Movie movie, int row, int col) {
        Seat[][] seats = show.getHall().getSeats();
        // 检查座位合法性
        if (row < 1 || row > seats.length || col < 1 || col > seats[0].length) {
            return null;
        }
        Seat seat = seats[row - 1][col - 1];
        if (seat.isSold()) {
            return null;
        }
        // 标记座位为已售
        seat.setSold(true);
        // 创建票
        Ticket ticket = new Ticket(show.getId(), movie.getName(), show.getHallName(),
                show.getTime(), row, col, show.getPrice());
        tickets.add(ticket);
        saveTickets();
        return ticket;
    }

    // 退票（需在放映前1小时以上）
    public boolean refundTicket(String ticketId) {
        Ticket ticket = getTicketById(ticketId);
        if (ticket == null || ticket.isRefunded()) {
            return false;
        }
        // 检查时间限制
        long timeDiff = ticket.getShowTime().getTime() - new Date().getTime();
        if (timeDiff < 3600 * 1000) { // 小于1小时
            return false;
        }
        // 标记为已退票
        ticket.setRefunded(true);
        // 释放座位
        ShowService showService = new ShowService(this);
        Show show = showService.getShowById(ticket.getShowId());
        if (show != null) {
            Seat seat = show.getHall().getSeats()[ticket.getRow() - 1][ticket.getCol() - 1];
            seat.setSold(false);
        }
        saveTickets();
        return true;
    }

    // 统计销售数据（按日/周/月）
    public SalesData getSalesData(String range) {
        SalesData data = new SalesData();
        Date now = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(now);

        // 设置时间范围起点
        if ("当日".equals(range)) {
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
        } else if ("当周".equals(range)) {
            calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
            calendar.set(Calendar.HOUR_OF_DAY, 0);
        } else if ("当月".equals(range)) {
            calendar.set(Calendar.DAY_OF_MONTH, 1);
            calendar.set(Calendar.HOUR_OF_DAY, 0);
        }
        Date startTime = calendar.getTime();

        // 统计数据
        for (Ticket ticket : tickets) {
            if (ticket.getSellTime().after(startTime) && ticket.getSellTime().before(now)) {
                if (ticket.isRefunded()) {
                    data.addRefund(ticket.getPrice());
                } else {
                    data.addSale(ticket.getPrice());
                }
            }
        }
        return data;
    }
}


